package com.bjfu.gmms.servlet.adminSecretaryServlet;

import com.bjfu.gmms.MyBatisUtil;
import com.bjfu.gmms.mapper.PhaseMapper;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/publishServlet")
public class PublishServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        String message = "";  // 用于存放操作结果信息
        boolean success = false;  // 标识操作是否成功

        try (SqlSession sqlSession = MyBatisUtil.getSqlSession("development")) {
            PhaseMapper phaseMapper = sqlSession.getMapper(PhaseMapper.class);

            if ("publish".equals(action)) {
                // 执行发布操作
                System.out.println("发布操作");
                int result = phaseMapper.updatePeriodByCollegeAndId(4, 5, 1);
                sqlSession.commit();  // 确保事务被提交
                if (result > 0) {
                    success = true;
                    message = "发布成功！";
                } else {
                    message = "发布失败，未能更新数据库。";
                }
            } else if ("cancelPublish".equals(action)) {
                // 执行取消发布操作
                System.out.println("取消发布操作");
                int result = phaseMapper.updatePeriodByCollegeAndId(4, 5, 0);
                sqlSession.commit();  // 确保事务被提交
                if (result > 0) {
                    success = true;
                    message = "取消发布成功！";
                } else {
                    message = "取消发布失败，未能更新数据库。";
                }
            }

            // 将操作结果信息作为响应发送到前端
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("<script type=\"text/javascript\">");
            if (success) {
                response.getWriter().write("alert('" + message + "');");
            } else {
                response.getWriter().write("alert('" + message + "');");
            }
            response.getWriter().write("window.location.href = 'allResultsQuery.jsp';</script>");
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("<script type=\"text/javascript\">");
            response.getWriter().write("alert('操作失败，数据库异常！');");
            response.getWriter().write("window.location.href = 'allResultsQuery.jsp';</script>");
        }
    }
}